/*!
 * jQuery Resize Event plugin
 * 
 * Copyright 2010, Anton Ilyuschenkov aka DriverX
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://driverx.su/license.html
 */
(function($, window, undefined){
	var	$window = $(window),
		documentIsLoaded,
		msie = $.browser.msie,
		anotherWindowNodes = [],
		specialHandlerInterval,
		nativeEventCall;
	
	if (msie) {
		$window.one("load", function(){
			documentIsLoaded = true;
			var	events = $.data(window, "events") || {},
				resizeHandlers = events.resize;
			removeSpecialNode(window);
			events.resize = undefined;
			$window.resize($.noop);
			events.resize = resizeHandlers;
		});
	}
	
	$.event.special.resize = {
		setup: function () {
			if (this === window && (!msie || documentIsLoaded)) {
				return false;
			} else {
				addSpecialNode(this);
			}
		},
		teardown: function () {
			if (this === window && (!msie || documentIsLoaded)) {
				return false;
			} else {
				removeSpecialNode(this);
			}
		}
	};
	
	function addSpecialNode (node) {
		node = $(node);
		var data = {
			$: node,
			w: node.width(),
			h: node.height()
		};
		if (anotherWindowNodes.push(data) == 1) {
			specialHandlerInterval = setInterval(function(){
				if (nativeEventCall) {
					nativeEventCall = !nativeEventCall;
				} else {
					specialHandler();
				} 
			}, 250);
		}
	}
	function removeSpecialNode (node) {
		var l = anotherWindowNodes.length;
		while (l--) {
			if (node === anotherWindowNodes[l].$[0]) {
				anotherWindowNodes.splice(l, 1);
			}
		}
		if (l == -1 && specialHandlerInterval) {
			clearInterval(specialHandlerInterval);
			specialHandlerInterval = nativeEventCall = null;
		}
	}
	
	if (window.addEventListener) {
		window.addEventListener("resize", specialHandler, false);
	} else if (window.attachEvent) {
		window.attachEvent("onresize", specialHandler);
	}
	function specialHandler (event) {
		if (event && event.type) {
			nativeEventCall = true;
		}
		$.each(anotherWindowNodes, function(i, data){
			var	node = data.$,
				currentWidth = node.width(),
				currentHeight = node.height();
			if (data.w != currentWidth || data.h != currentHeight) {
				data.w = currentWidth;
				data.h = currentHeight;
				node.triggerHandler("resize");
			}
		});
	}
})(jQuery, window);